#!/usr/bin/env bash

#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#

set -e

DOWNLOAD_MB=${1:-1000}
UPLOAD_MB=${2:-0}
SERVER=${3:-s2n-quic}
CLIENT=${4:-s2n-quic}
DURATION=${6-10}

TEST="${DOWNLOAD_MB}MB-down-${UPLOAD_MB}MB-up"
TITLE="${DOWNLOAD_MB}MB Download, ${UPLOAD_MB}MB Upload"
DOWNLOAD_BYTES=$(($DOWNLOAD_MB * 1000000))
UPLOAD_BYTES=$(($UPLOAD_MB * 1000000))

TMP_DIR=$(mktemp -d -t s2n-quic-perf-XXXXXXXXXX)
OUT_DIR="$(pwd)/target/perf/results/${CLIENT}-client-${SERVER}-server"
mkdir -p $OUT_DIR

cd scripts/perf
SERVER=$SERVER \
  CLIENT=$CLIENT \
  DOWNLOAD_BYTES=$DOWNLOAD_BYTES \
  UPLOAD_BYTES=$UPLOAD_BYTES \
  DURATION=$DURATION \
  SERVER_PORT=4433 \
  TMP_DIR=$TMP_DIR \
  OUT_DIR=$OUT_DIR \
  TEST=$TEST \
  S2N_UNSTABLE_CRYPTO_OPT_TX=1 \
  S2N_UNSTABLE_CRYPTO_OPT_RX=1 \
  ultraman start --no-timestamp true

function report() {
  echo "$1 - generating report"
  TMP_DIR=$TMP_DIR \
    OUT_DIR=$OUT_DIR \
    TEST=$TEST \
    PS="$1.1" \
    ./bin/report

  if [ -f "$OUT_DIR/$TEST.$1.1.stacks" ]; then
    echo "$1 - generating flamegraph"
    inferno-flamegraph "$OUT_DIR/$TEST.$1.1.stacks" \
      --title "$2 $1 ($TLS) - $TITLE" \
      > $OUT_DIR/$TEST.$1.svg

    echo "$1 - flamegraph available in $OUT_DIR/$TEST.$1.svg"
  fi
}

report client $CLIENT
report server $SERVER

rm -rf $TMP
